package biz.appframe;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.data.domain.Page;

public class PageJsonBean implements Serializable {

	private static final long serialVersionUID = -7250621301497041370L;

	private Integer total = 0;

	@SuppressWarnings("rawtypes")
	private List<?> rows=new ArrayList();
	
	@SuppressWarnings("rawtypes")
	private List<?> footer=new ArrayList();

	public List<?> getFooter() {
		return footer;
	}

	public void setFooter(List<?> footer) {
		this.footer = footer;
	}

	public Integer getTotal() {
		return total;
	}

	public void setTotal(Integer total) {
		this.total = total;
	}

	public List<?> getRows() {
		return rows;
	}

	public void setRows(List<?> rows) {
		this.rows = rows;
	}
	
	public static PageJsonBean fromPage(Page<?> page){
		PageJsonBean pageJsonBean = new PageJsonBean();
		pageJsonBean.setTotal(new Long(page.getTotalElements()).intValue());
		pageJsonBean.setRows(page.getContent());
		return pageJsonBean;
	}

	public static String toJson(Page<?> page){
		String retVal = "";
		PageJsonBean pageJsonBean = fromPage(page);
		ObjectMapper mapper = new BizObjectMapper();
		try {
			retVal = mapper.writeValueAsString(pageJsonBean);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return retVal;
	}
	/**
	 * 将一个Object对象使用输出流输出
	 * @param response HttpServletResponse对象
	 * @param object Object对象
	 */
	public static void printObject(HttpServletResponse response, Object object){
		PrintWriter writer = null;
		try {
			response.setCharacterEncoding("UTF-8");
			writer = response.getWriter();
			writer.println(object);
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if(null != writer){
				writer.close();
			}
		}
	}
}
